<template>
    <div style="width: 100%;height: 100%;" ref="chart"></div>
</template>

<script>
import * as echarts from "echarts";
import request from "@/utils/request";

export default {
    name: "pieChart",
    data() {
        return {
            chart: []
        };
    },
    mounted() {
        this.getData();
        window.addEventListener("resize", this.resizeChart); // 绑定 resizeChart 方法
    },
    methods: {
        async getData() {
            const { data: res } = await request.get("/views/gradeBorrowedCountPie");
            let i = 0;
            Object.keys(res).forEach((key) => {
                let obj = {};
                obj.value = res[key];
                obj.name = key;
                this.chart[i] = obj;
                i++;
            });
            this.echartsInit();
        },
        echartsInit() {
            let chart = this.chart;
            echarts
                .init(this.$refs.chart) // 使用 ref 引用图表容器
                .setOption({
                    title: {
                        text: "各年级分布的读者数量",
                        left: "center",
                        textStyle: {
                            color: "#fff"
                        }
                    },

                    tooltip: {
                        trigger: "item"
                    },
                    legend: {
                        textStyle: {
                            color: "#fff"
                        },
                        top: "15px",
                        left: "center"
                    },
                    series: [
                        {
                            name: "date",
                            type: "pie",
                            radius: ["50%", "70%"],
                            avoidLabelOverlap: false,
                            data: chart,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: "#fff",
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: "center"
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 20,
                                    fontWeight: "bold",
                                    color: "#fff"
                                }
                            }
                        }
                    ],

                    responsive: true // 启用响应式布局
                });

        },
        resizeChart() {
            this.chart.resize(); // 更新图表大小
        }
    },
    beforeDestroy() {
        window.removeEventListener("resize", this.resizeChart); // 移除 resize 事件监听器
    }
};
</script>

<style scoped>
</style>
